﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeighSystem.Interface
{
    using System;
    using System.IO.Ports;
    using WeighSystem.Class;

    class SerialPortHelper
    {
        private long _receiveByteCount = 0, _sendByteOfCount = 0;


        public long ReceiveByteCount { get { return _receiveByteCount; } set { _receiveByteCount = value; } }
        public long SendByteOfCount { get { return _sendByteOfCount; } set { _sendByteOfCount = value; } }


        SerialPort _serialPort = new SerialPort();


        public class DataReceivedEventArgs : EventArgs
        {
            public Byte[] DataReceived;
            public DataReceivedEventArgs(byte[] m_DataReceived)
            {
                this.DataReceived = m_DataReceived;
            }
        }


        public delegate void DataReceivedEventHandler(DataReceivedEventArgs e);


        public event DataReceivedEventHandler DataReceived;
        public event SerialErrorReceivedEventHandler Error;

        public bool IsOpen { get { return _serialPort.IsOpen; } }
        public SerialPortHelper(string PortName, int BaudRate,bool hasNewLine =false)
        {
            _serialPort.PortName = PortName;
            _serialPort.StopBits = StopBits.One;
            _serialPort.Parity = Parity.None;
            _serialPort.DataBits = 8;
            _serialPort.BaudRate = BaudRate;
            if(hasNewLine)
            _serialPort.NewLine = "\r\n";
            _serialPort.DataReceived += _serialPort_DataReceived;
            _serialPort.PinChanged += _serialPort_PinChanged;
        }
        public class SerialPortDataEventArgs : EventArgs
        {
            public byte[] data { get; set; }
        }
        private void _serialPort_PinChanged(object sender, SerialPinChangedEventArgs e)
        {
            Console.WriteLine("Pin chaged");
        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(20);


            int ReadLength = _serialPort.BytesToRead;
            if (ReadLength > 0)
            {
                byte[] ReadBuffer = new byte[ReadLength];
                _serialPort.Read(ReadBuffer, 0, ReadLength);
                FileLog.WriteLogToFile(FileLog.LOGLEVEL.信息, ReadBuffer, ReadLength);
                //string readString = _serialPort.ReadLine();
               // FileLog.WriteLogToFile(FileLog.LOGLEVEL.信息,readString);
                //_receiveByteCount = (Encoding.ASCII.GetBytes(readString)).Count();
                //ReadBuffer = new byte[_receiveByteCount];
                //ReadBuffer = Encoding.ASCII.GetBytes(readString);
                //_serialPort.Read(ReadBuffer, 0, ReadLength);
                //触发整条记录的处理
                if (DataReceived != null)
                {
                    DataReceived(new DataReceivedEventArgs(ReadBuffer));
                }
            }
        }

        public static string[] SerialPortNames
        {
            get
            {
                string[] serialports = SerialPort.GetPortNames();
                Array.Sort(serialports, new Comparison<string>(
                    delegate (string x, string y)
                    {
                        if (x.Length > 3 && y.Length > 3)
                        {
                            string index1 = x.Substring(3);
                            string index2 = y.Substring(3);
                            try
                            {
                                int n1 = Convert.ToInt32(index1);
                                int n2 = Convert.ToInt32(index2);
                                return n1 - n2;
                            }
                            catch
                            {
                            }
                        }
                        return 0;
                    }));
                return serialports;
            }
        }

        /*
        public SerialPortHelper(DataReceived received)
        {
            _received = received;
            _serialPort.NewLine = "\r\n";
            _serialPort.DataReceived += delegate
            {
                System.Threading.Thread.Sleep(50);
                int ReadLength = _serialPort.BytesToRead;
                if (ReadLength > 0)
                {
                    _receiveByteCount += ReadLength;
                    byte[] ReadBuffer = new byte[ReadLength];
                    _serialPort.Read(ReadBuffer, 0, ReadLength);
                    if (_received != null)
                    {
                        _received(ReadBuffer);
                    }
                }
            };
        }


        public SerialPortHelper(StateChange stateChanged)
        {
            _stateChanged = stateChanged;
           // _serialPort.PinChanged += _stateChanged;
        }
        */

        public void Open()
        {

            _serialPort.Open();
        }


        public void Close()
        {
            if(_serialPort.IsOpen)
            _serialPort.Close();
        }


        public void WriteLine(string text)
        {
            if (_serialPort.IsOpen)
            {
                _sendByteOfCount += text.Length;
                _serialPort.WriteLine(text);
            }
        }


        public void Write(byte[] buffer)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Write(buffer, 0, buffer.Length);
                _sendByteOfCount += buffer.Length;
            }
        }
    }

}
